<template>
  <user-search
    ref="searchRef"
    style="margin-bottom: -14px"
    @search="reload"
    :cache-key="getCurrentInstance().type.name"
  />
  <ele-pro-table
    ref="tableRef"
    row-key="user_id"
    :pagination="pagination"
    :loading="loading"
    :columns="columns"
    :datasource="datasource"
    v-model:selections="selections"
    :highlight-current-row="true"
    :export-config="{
      fileName: '用户数据',
      datasource: exportSource,
      tableName: getCurrentInstance().type.name,
    }"
    :print-config="{ datasource: exportSource }"
    :style="{ paddingBottom: '16px' }"
    :cache-key="getCurrentInstance().type.name"
  >
    <template #toolbar>
      <el-button
        type="primary"
        class="ele-btn-icon"
        :icon="PlusOutlined"
        @click="openAdd()"
      >
        新建
      </el-button>
      <el-button
        type="danger"
        class="ele-btn-icon"
        :icon="DeleteOutlined"
        @click="action('remove')"
      >
        删除
      </el-button>
      <el-button
        class="ele-btn-icon"
        :icon="UploadOutlined"
        @click="openImport"
      >
        导入
      </el-button>
    </template>
    <template #nickname="{ row }">
      <el-link type="primary" underline="never" @click="openDetail(row)">
        {{ row.nickname }}
      </el-link>
    </template>
    <template #roles="{ row }">
      <el-tag
        v-for="item in row.roles"
        :key="item.role_id"
        size="small"
        :disable-transitions="true"
      >
        {{ item.role_name }}
      </el-tag>
    </template>
    <template #status="{ row }">
      <el-switch
        size="small"
        :model-value="row.status === 1"
        @change="(checked) => editStatus(checked, row)"
      />
    </template>
    <template #action="{ row }">
      <!-- <el-link type="primary" underline="never" @click="openView(row)">
        查看
      </el-link>
      <el-divider direction="vertical" /> -->
      <el-link type="primary" underline="never" @click="openEdit(row)">
        修改
      </el-link>
      <el-divider direction="vertical" />
      <ele-dropdown
        :items="[
          { title: '重置密码', command: 'password' },
          { title: '删除用户', command: 'delete', danger: true, divided: true },
        ]"
        style="display: inline"
        @command="(key) => dropClick(key, row)"
      >
        <el-link type="primary" underline="never">
          <span>更多</span>
          <el-icon :size="12" style="vertical-align: -1px; margin-left: 2px">
            <ArrowDown />
          </el-icon>
        </el-link>
      </ele-dropdown>
    </template>
  </ele-pro-table>
  <!-- 新增 -->
  <user-edit
    action="add"
    :organization_id="organization_id"
    v-model="showAdd"
    @done="reload"
  />

  <!-- 修改 -->
  <user-edit
    action="edit"
    :organization_id="organization_id"
    :data="current"
    v-model="showEdit"
    @done="reload"
  />

  <!-- 查看 -->
  <user-edit
    action="view"
    :organization_id="organization_id"
    :data="current"
    v-model="showView"
  />
  <user-import v-model="showImport" @done="reload" />
</template>

<script setup>
import { ref, watch, getCurrentInstance } from "vue";
import { useRouter } from "vue-router";
import { ElMessageBox } from "element-plus/es";
import { EleMessage } from "ele-admin-plus/es";

import {
  PlusOutlined,
  DeleteOutlined,
  ArrowDown,
  UploadOutlined,
} from "@/components/icons";
import { usePageTab } from "@/utils/use-page-tab";
import UserSearch from "./user-search.vue";
import UserEdit from "./user-edit.vue";
import UserImport from "./user-import.vue";
import { useDictData } from "@/utils/use-dict-data";
import { getTypeName } from "@/utils/function";
import { useTable } from "@/hooks/useTable";
import { useOperator } from "@/hooks/operator";
import { useModal } from "@/hooks/useModal";

import {
  pageUsers,
  removeUsers,
  updateUserStatus,
  updateUserPassword,
  listUsers,
} from "@/api/system/user";

const props = defineProps({
  /** 机构 id */
  organization_id: Number,
});
defineOptions({ name: "SystemUserTable" });

const { push } = useRouter();
const { addPageTab } = usePageTab();
const [sexDicts] = useDictData(["sex"]);

/** 搜索栏实例 */
const searchRef = ref(null);

/** 表格列配置 */
const columns = ref([
  {
    type: "selection",
    columnKey: "selection",
    width: 50,
    align: "center",
    fixed: "left",
  },
  {
    type: "index",
    columnKey: "index",
    width: 50,
    align: "center",
    fixed: "left",
  },
  {
    prop: "username",
    label: "用户账号",
    sortable: "custom",
    minWidth: 110,
  },
  {
    prop: "nickname",
    label: "用户名",
    sortable: "custom",
    minWidth: 110,
    slot: "nickname",
  },
  {
    prop: "job_number",
    label: "工号",
    minWidth: 80,
    slot: "job_number",
  },
  {
    prop: "sex",
    label: "性别",
    sortable: "custom",
    width: 90,
    align: "center",
    formatter: (row) => {
      return getTypeName(sexDicts.value, row, "sex");
    },
  },
  {
    columnKey: "roles",
    label: "角色",
    minWidth: 110,
    slot: "roles",
    align: "center",
    formatter: (row) => row.roles.map((d) => d.role_name).join(","),
  },
  {
    prop: "created_at",
    label: "创建时间",
    sortable: "custom",
    width: 160,
    align: "center",
  },
  {
    prop: "status",
    label: "状态",
    width: 80,
    align: "center",
    sortable: "custom",
    slot: "status",
    formatter: (row) => (row.status == 1 ? "正常" : "冻结"),
  },
  {
    columnKey: "action",
    label: "操作",
    width: 110,
    fixed: "right",
    align: "center",
    slot: "action",
    hideInPrint: true,
    hideInExport: true,
  },
]);

const {
  loading,
  pagination,
  tableRef,
  datasource,
  reload,
  current,
  selections,
} = useTable({
  getPages: pageUsers,
  beforeQuery: (params) => {
    // 可以修改或添加查询参数
    console.log("查询参数:", params); // 调试用，实际不需要这一行
    return {
      ...params,
      ...params.where,

      organization_id: props.organization_id,
    };
  },
  afterQuery: () => {
    // 查询后处理
  },
});

// 使用hook创建各个弹窗
const { visible: showAdd, open: openAdd } = useModal({
  beforeOpen: async () => {
    current.value = null; // 新增时重置数据
    // if (!props.dict_ids) {
    //   throw new Error("请先选择字典");
    // }
  },
});

const { visible: showEdit, open: openEdit } = useModal({
  beforeOpen: async (row) => {
    current.value = row; // 设置当前行数据
    // if (!row?.editable) {
    //   throw new Error("没有编辑权限");
    // }
  },
});

const { visible: showView, open: openView } = useModal({
  beforeOpen: async (row) => {
    current.value = row; // 设置当前行数据
  },
});

/** 是否显示用户导入弹窗 */
const showImport = ref(false);

/** 打开编辑弹窗 */
const openImport = () => {
  showImport.value = true;
};

/** 删除 */
// 替换原有的remove方法
const { action } = useOperator({
  actionConfigs: {
    remove: {
      title: "删除",
      confirmText: "确定要删除{%s}这些数据吗?",
      api: removeUsers,
      beforeSubmit: (params) => {
        // 可以修改或添加提交参数
        console.log("[DEBUG] beforeSubmit 钩子被调用", params);
        return params; // 必须返回处理后的参数
      },
    },
    status: {
      title: "状态",
      confirmText: "确定要切换为{%s}这些数据吗?",
      api: updateUserStatus,
      skipConfirm: true,
      beforeSubmit: (params) => {
        // 可以修改或添加提交参数
        // const status = checked ? 0 : 1;
        console.log("[DEBUG] beforeSubmit 钩子被调用", params);
        return params; // 必须返回处理后的参数
      },
    },
  },
  selections,
  reload,
  idField: "user_id",
  idName: "nickname",
});

/** 修改用户状态 */
const editStatus = (checked, row) => {
  console.log("editStatus", checked, row);
  const status = checked ? 1 : 0;
  action("status", row, {
    status: status,
    statusText: status ? "正常" : "冻结",
  });
};

/** 下拉菜单点击事件 */
const dropClick = (key, row) => {
  if (key === "password") {
    ElMessageBox.prompt(`请输入用户"${row.nickname}"的新密码：`, "重置密码", {
      inputPattern: /^[\S]{5,18}$/,
      inputErrorMessage: "密码必须为5-18位非空白字符",
      draggable: true,
    })
      .then(({ value }) => {
        const loading = EleMessage.loading({
          message: "请求中..",
          plain: true,
        });
        updateUserPassword(row.user_id, value)
          .then((msg) => {
            loading.close();
            EleMessage.success(msg);
          })
          .catch((e) => {
            loading.close();
            EleMessage.error(e.message);
          });
      })
      .catch(() => {});
  } else if (key === "delete") {
    action("remove", row);
  }
};

// 监听机构 id 变化
watch(
  () => props.organization_id,
  () => {
    searchRef.value?.resetFields?.();
    reload({});
  },
);

/** 导出和打印全部数据的数据源 */
const exportSource = ({ where, orders }) => {
  return listUsers({
    ...where,
    ...orders,
    organization_id: props.organization_id,
  });
};

/** 查看详情 */
const openDetail = (row) => {
  const path = `/system/user/details/${row.user_id}`;
  addPageTab({
    title: `用户详情[${row.nickname}]`,
    key: path,
    closable: true,
    meta: { icon: "UserOutlined" },
  });
  push(path);
};
</script>
